/**
 * Created with JetBrains WebStorm.
 * User: Tianshaokai
 * Date: 14-16-17
 * Time: 16:17
 * To change this template use File | Settings | File Templates.
 */

var config = require('app-config').config;
var fs = require('fs-extra');
var mongoose = require('mongoose');
var EventProxy = require('eventproxy');
var log4js = require('log4js');
var logger = log4js.getLogger('normal');
var qn = require('qn');

var crypto = require('crypto');

exports.containObjInArray = function(object,array){
    var index = -1;
    for(var i = 0; i < array.length; i ++){
        if(exports.compareObject(array[i],object)) {
            index = i;
        }
    }
    return index != -1;
};
exports.compareObject = function(o1,o2){
    if(typeof o1 != typeof o2)return false;
    if(typeof o1 == 'object'){
        for(var o in o1){
            if(typeof o2[o] == 'undefined')return false;
            if(!this.compareObject(o1[o],o2[o]))return false;
        }
        return true;
    }else{
        return o1 === o2;
    }
};

exports.isEmptyObject = function( obj ) {
    for ( var name in obj ) {
        return false;
    }
    return true;
}


/**
 *
 * @param originObject需要排序数组  x
 * @param targetObject目标数组  m
 * @constructor
 */
exports.ArraySort = function(originObject,targetObject){
        var result = [];
        for(var i=0;i<targetObject.length;i++){

            for(var j=0;j<originObject.length;j++){
                if(originObject[j]._id.equals(targetObject[i])){
                    result.push(originObject[j]);
                    break;
                }
            }
        }
    return  result;
}

exports.format_date = function (date, friendly) {
    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var minute = date.getMinutes();
    var second = date.getSeconds();

    if (friendly) {
        var now = new Date();
        var mseconds = -(date.getTime() - now.getTime());
        var time_std = [ 1000, 10*1000, 60 * 1000, 60 * 60 * 1000, 24 * 60 * 60 * 1000 ];
        if (mseconds < time_std[4]) {
            if (mseconds > 0 && mseconds < time_std[1]) {
                return '刚刚';
            }
            if (mseconds > time_std[1] && mseconds < time_std[2]) {
                return Math.floor(mseconds / time_std[0]).toString() + ' 秒前';
            }
            if (mseconds > time_std[2] && mseconds < time_std[3]) {
                return Math.floor(mseconds / time_std[2]).toString() + ' 分钟前';
            }
            if (mseconds > time_std[3]) {
                return Math.floor(mseconds / time_std[3]).toString() + ' 小时前';
            }
        }
    }

    //month = ((month < 10) ? '0' : '') + month;
    //day = ((day < 10) ? '0' : '') + day;
    hour = ((hour < 10) ? '0' : '') + hour;
    minute = ((minute < 10) ? '0' : '') + minute;
    second = ((second < 10) ? '0': '') + second;

    var thisYear = new Date().getFullYear();
    year = (thisYear === year) ? '' : (year + '-');
    return year + month + '-' + day + ' ' + hour + ':' + minute;
};

exports.format_customer = function(d, format) {
//        {date} d
//        日期
//        {string} format
//        日期格式：yyyy-MM-dd w hh:mm:ss
//        yyyy/yy 表示年份
//        MM/M 月份
//        w 星期
//        dd/d 日
//        hh/h 小时
//        mm/m 分
//        ss/s 秒

    var str = format;
    var Week = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    var month = d.getMonth() + 1;

    str = str.replace(/yyyy/, d.getFullYear());
    str = str.replace(/yy/, (d.getYear() % 100) > 9 ? (d.getYear() % 100).toString() : '0' + (d.getYear() % 100));
    str = str.replace(/MM/, month > 9 ? month.toString() : '0' + month);
    str = str.replace(/M/g, month);
    str = str.replace(/dd/, d.getDate() > 9 ? d.getDate().toString() : '0' + d.getDate());
    str = str.replace(/d/g, d.getDate());

    str = str.replace(/w/g, Week[d.getDay()]);

    str = str.replace(/hh/, d.getHours() > 9 ? d.getHours().toString() : '0' + d.getHours());
    str = str.replace(/h/g, d.getHours());
    str = str.replace(/mm/, d.getMinutes() > 9 ? d.getMinutes().toString() : '0' + d.getMinutes());
    str = str.replace(/m/g, d.getMinutes());
    str = str.replace(/ss/, d.getSeconds() > 9 ? d.getSeconds().toString() : '0' + d.getSeconds());
    str = str.replace(/s/g, d.getSeconds());
    return str;
}


/*
 pageNum 第几页
 totalNum 总记录数
 */
exports.page = function(pageNum, totalNum,limit)
{
    var result = {};
    pageNum = pageNum > 0 ? pageNum : 1;
    result.limit = limit || config.list_topic_count;       //每页显示的记录数
    //总页数
    result.totalPage = Math.ceil(totalNum / result.limit) || 1; //如果没有记录，默认为1页
    result.pageNum = pageNum;


    if (pageNum > result.totalPage)
    {
        result.pageNum = result.totalPage;
    }
    result.skip = result.limit * (result.pageNum - 1); //计算从第几条记录开始显示
    return result;
}


//上传背景图
exports.uploadErrorZip = function(fileArray, filepath, callback){
    var this_file_path = filepath|| config.upload_error_zip;
    if(fileArray==undefined){
        return callback(null, null);
    }
    var proxy = new EventProxy();
    var fileKeys = Object.keys(fileArray);
    if (fileKeys.length === 0) {
        return callback(null, null);
    }
    proxy.fail(function(err){
        return callback(err);
    })
    proxy.after('tag_saved', fileKeys.length, function(imgIds){
        var filtered = imgIds.filter(function (item) {
            if(item.id!=""){
                return true
            }else{
                return false;
            }
        });
        return callback(null, filtered);
    });
    fileKeys.forEach(function (file) {
        var json = {};
        var name = fileArray[file].name;
        var tmp_path = fileArray[file].path;
        var fileType =  fileArray[file].type;
        var imgID = exports.validPic(fileType);
        json.name = file;
        if(name==""||imgID==null){
            fs.remove(tmp_path, function(err) {
                if(err){
                    logger.error('fs.remove error------',err);
                }
                json.id="";
                proxy.emit('tag_saved', json);
            });
        }else{
            var target_path =  this_file_path + imgID ;
            json.id= imgID;
            fs.rename(tmp_path, target_path,function (err) {
                if (err) {
                    logger.error('fs.rename error------', err);
                }
                proxy.emit('tag_saved', json);
            });
        }
    });
}
//获得文件后缀
exports.validPic = function(type) {
    var suffix = type.split('/')[1];
        var _id = mongoose.Types.ObjectId();
        return  _id + '.' + suffix;
}

/**
 * 检查参数是否为空
 * 返回true表示不为空,false表示为空
 * @param params
 * @returns {boolean}
 */
exports.checkBlank = function(params){
    var flag = true;
    if(params instanceof Array){
        for(var i=0;i<params.length;i++){
            if(params[i] == null || params[i] == 'null' || params[i] ==''){
                flag = false;
                break;
            }
        }
    }else{
        if(params == null || params == 'null' || params==''){
            flag =  false;
        }
    }
    return flag;
}

/**
 *
 * @param str
 * @param toUpperCase 是否大写
 * @returns {*}
 */
exports.md5 = function (str,toUpperCase) {
    var md5sum = crypto.createHash('md5');
    md5sum.update(str);
    str = md5sum.digest('hex');
    if(toUpperCase!==null&&toUpperCase){
        str = str.toUpperCase();
    }
    return str;
};

//判断是不是手机号
exports.isMobile = function(str){
    return (/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/.test(str));
}

//生成随机字符串
exports.getRandomString = function getRandomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
};

//生成随机字符串(所有的，没去掉混淆字符)
exports.getAllRandomString = function getAllRandomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var maxPos = $chars.length;
    var pwd = '';
    for (var i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
};